//
//  MineHistoryManager.m
//  House
//
//  Created by 吕品 on 2016/9/13.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "MineHistoryManager.h"
#import "YTKKeyValueStore.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDB.h"
static NSString * const rent = @"historyRents";
static NSString * const secondary = @"historySecondarys";
@implementation MineHistoryManager

+ (void)storeItemID:(NSString* )itemid withType:(NSInteger)type{
    [self createTableWithType:type];
    if (type == 7) {
        [[self YTKStore] putString:itemid withId:itemid intoTable:rent];
    } else {
        [[self YTKStore] putString:itemid withId:itemid intoTable:secondary];
    }
}
+ (NSArray *)getInfoWithType:(NSInteger)type andNumber:(NSInteger)number{
    NSArray *arr;
    if (type == 7) {
        arr = [self getAllItemsFromTable:rent];
    } else {
        arr = [self getAllItemsFromTable:secondary];
    }
    NSMutableArray *array = [NSMutableArray array];
    NSInteger page;
    if (number == 0 || arr.count < number) {
        return arr;
    } else {
        page = number;
    }
    for (NSInteger i = 0; i < page; i ++) {
        [array addObject:arr[i]];
        NSLog(@"%@", arr[i]);
    }
    return array;
}

+ (YTKKeyValueStore *)YTKStore {
    YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"history.sqlite"];
    return store;
}

+ (void)createTableWithType:(NSInteger)type {
    if (type == 7) {
        [[self YTKStore] createTableWithName:rent];
    } else {
        [[self YTKStore] createTableWithName:secondary];
    }
}

+ (NSArray *)getAllItemsFromTable:(NSString *)tableName {
    NSString * sql = [NSString stringWithFormat:@"SELECT * from %@", tableName];
    __block NSMutableArray * result = [NSMutableArray array];
    [[FMDatabaseQueue databaseQueueWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"history.sqlite"]] inDatabase:^(FMDatabase *db) {
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
            [result addObject:[rs stringForColumn:@"id"]];
        }
        [rs close];
    }];
    return result;
}

@end



